package com.dal.common.utils;

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class TxtParser {

    public static void main(String[] args) throws Exception {
        String filePath = "/Users/jian/Desktop/registry/1.txt";
        List<Map<String, Object>> dataList = new ArrayList<>();
        Set<String> fields = new LinkedHashSet<>();
        Map<String, String> fieldTypes = new HashMap<>();

        // 解析文件并收集字段信息
        parseFile(filePath, dataList, fields, fieldTypes);

        // 生成Java类
        generateJavaClass(fields, fieldTypes, "DataObject");

        // 生成SQL建表语句
        String createTableSql = generateCreateTableSql(fields, fieldTypes, "data_table");
        System.out.println("生成的SQL建表语句：\n" + createTableSql);

        // 生成插入语句
        String insertSql = generateInsertSql(fields);
        System.out.println("\n生成的SQL插入语句：\n" + insertSql);

        // 在main方法中添加调用
        List<String> insertStatements = generateConcreteInsertSql(dataList, fields, "data_table");
        System.out.println("\n生成的具体插入语句："+insertStatements.size());
        insertStatements.forEach(System.out::println);
    }

    private static void parseFile(String filePath, List<Map<String, Object>> dataList,
                                  Set<String> fields, Map<String, String> fieldTypes) throws IOException {
        Pattern pattern = Pattern.compile("(\\w+)\\s*:\\s*(?:'([^']*)'|(\\d+))");
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                Map<String, Object> row = new HashMap<>();
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()) {
                    String key = matcher.group(1);
                    String strValue = matcher.group(2);
                    String numValue = matcher.group(3);

                    Object value;
                    String type;
                    if (strValue != null) {
                        value = strValue;
                        type = "String";
                    } else {
                        value = Long.parseLong(numValue); // 使用Long以支持更大数字
                        type = key.startsWith("is_") ? "Boolean" : "Long";
                    }

                    row.put(key, value);
                    if (!fieldTypes.containsKey(key)) {
                        fieldTypes.put(key, type);
                        fields.add(key);
                    }
                }
                dataList.add(row);
            }
        }
    }

    private static void generateJavaClass(Set<String> fields, Map<String, String> fieldTypes, String className) {
        StringBuilder sb = new StringBuilder();
        sb.append("public class ").append(className).append(" {\n");

        // 生成字段
        for (String field : fields) {
            String type = fieldTypes.get(field);
            String javaType = "String";
            if ("Long".equals(type)) javaType = "Long";
            else if ("Boolean".equals(type)) javaType = "Boolean";
            sb.append("    private ").append(javaType).append(" ").append(toCamelCase(field)).append(";\n");
        }

        // 生成getter和setter
        for (String field : fields) {
            String type = fieldTypes.get(field);
            String javaType = "String";
            if ("Long".equals(type)) javaType = "Long";
            else if ("Boolean".equals(type)) javaType = "Boolean";
            String camelField = toCamelCase(field);

            sb.append("\n    public ").append(javaType).append(" get").append(capitalize(camelField)).append("() {\n")
              .append("        return this.").append(camelField).append(";\n    }\n");

            sb.append("\n    public void set").append(capitalize(camelField)).append("(")
              .append(javaType).append(" ").append(camelField).append(") {\n")
              .append("        this.").append(camelField).append(" = ").append(camelField).append(";\n    }\n");
        }

        sb.append("}\n");
        System.out.println("生成的Java类：\n" + sb.toString());
    }

    private static String generateCreateTableSql(Set<String> fields, Map<String, String> fieldTypes, String tableName) {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE ").append(tableName).append(" (\n");
        List<String> columns = new ArrayList<>();
        for (String field : fields) {
            String type = fieldTypes.get(field);
            String sqlType;
            switch (type) {
                case "String": sqlType = "VARCHAR(255)"; break;
                case "Boolean": sqlType = "TINYINT(1)"; break;
                default: sqlType = "BIGINT"; // 处理Long类型
            }
            columns.add("    " + field + " " + sqlType);
        }
        sb.append(String.join(",\n", columns));
        sb.append("\n);");
        return sb.toString();
    }

    private static String generateInsertSql(Set<String> fields) {
        return "INSERT INTO data_table (" + String.join(", ", fields) + ")\n" +
               "VALUES (" + String.join(", ", Collections.nCopies(fields.size(), "?")) + ");";
    }

    private static String toCamelCase(String s) {
        StringBuilder sb = new StringBuilder();
        for (String part : s.split("_")) {
            if (sb.length() == 0) sb.append(part);
            else sb.append(part.substring(0, 1).toUpperCase()).append(part.substring(1));
        }
        return sb.toString();
    }

    private static String capitalize(String s) {
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }


    // 在原有类中添加以下方法
    private static List<String> generateConcreteInsertSql(List<Map<String, Object>> dataList,
                                                          Set<String> fields,
                                                          String tableName) {
        List<String> sqlList = new ArrayList<>();
        for (Map<String, Object> row : dataList) {
            StringBuilder fieldsSb = new StringBuilder();
            StringBuilder valuesSb = new StringBuilder();

            for (String field : fields) {
                // 处理字段名
                if(fieldsSb.length() > 0) fieldsSb.append(", ");
                fieldsSb.append(field);

                // 处理字段值
                if(valuesSb.length() > 0) valuesSb.append(", ");
                Object value = row.getOrDefault(field, null);

                // 类型转换处理
                if(value == null) {
                    valuesSb.append("NULL");
                } else if(value instanceof String) {
                    valuesSb.append("'").append(escapeSql((String)value)).append("'");
                } else if(value instanceof Boolean) {
                    valuesSb.append((Boolean)value ? "1" : "0");
                } else {
                    valuesSb.append(value);
                }
            }

            sqlList.add(String.format("INSERT INTO %s (%s)\nVALUES (%s);",
                    tableName,
                    fieldsSb.toString(),
                    valuesSb.toString()));
        }
        return sqlList;
    }

    // SQL特殊字符转义方法
    private static String escapeSql(String str) {
        return str.replace("'", "''");
    }


}